
var wxTimer = require('../../wxTimer.js');
var ScanBar = require("../../plugin/scan/scanbar.js");
const config = require('../../config');
const queryStatus = config.queryStatus;
const $ = require('../../utils/utils');

var queryStatusIntervarID;
var wxTimerId;
var app = getApp();
Page({
    data: {
        startScanFlag: 0,
        doorStatus: -1,
        overTimeFlag: 0,
        wish_list: [],
        isWishView: 0
    },



    onLoad: function (res) {
        $.hideLoading()
        console.log('# borrowing_onLoad()', res);
        var that = this;
        if (res.path == "bookDetail") {

            let bookDetailData = []
            bookDetailData.push(JSON.parse(wx.getStorageSync("bookDetailData")))
            if (bookDetailData.length != 0) {
                that.setData({
                    isWishView: 1
                });
            }
            that.setData({
                wish_list: bookDetailData
            });
            wx.removeStorageSync("bookDetailData")

        } else if (res.path == "wishList") {
            let wishlist = wx.getStorageSync("wish_bookgrid").wishList
            that.setData({
                wish_list: wishlist,
                isWishView: 1
            })
            wx.removeStorageSync("wish_bookgrid")
        } else {
            // 获取心愿单列表
            that.wish_list_item();
        }
        console.log('overTimeFlag' + JSON.stringify(res));
        if (res.overTimeFlag) {
            that.setData({
                doorStatus: 1,
                overTimeFlag: 1
            });
        }//超时等待界面

    },

    onShow: function (overTimeFlag) {
        console.log('# logs_onShow()', overTimeFlag)
        var that = this;

        wx.setStorageSync('detailStatus', false);//暂时还书界面标志
        wx.connectSocket({
            url: config.wsUrl + "?action=app&token=" + wx.getStorageSync('usertoken') + "&userid=" + wx.getStorageSync('userid'),
            header: { 'content-type': 'application/json' },
            success: function (res) {
                console.info('socket连接建立' + JSON.stringify(res));
            }
        });

        wx.onSocketMessage(function (res) {

            console.log('收到websocket响应:' + res.data);
            var action = JSON.parse(res.data).action;
            if ("unlock_success" === action) { //开柜成功
                that.handleStatus('1');
                return;
            } else if ("unlock_failed" === action) {  //开柜失败
                that.handleStatus('2');
                return;
            } else if ("lock_success" === action) {  //关柜成功
                that.handleStatus('3');
                return;
            } else if ("stocktaking_success" === action) {  //盘点成功
                that.handleStatus('5');
                return;
            }

        });

        //首先定时查询书柜门的状态，关闭之后跳转另外定时执行 
        queryStatusIntervarID = setInterval(function () {
            //跳转页面之后不再请求
            if (!wx.getStorageSync('detailStatus')) {
                let data = {
                    grid_code: wx.getStorageSync('grid_code'),
                    userid: wx.getStorageSync('userid'),
                    usertoken: wx.getStorageSync('usertoken')
                }

                let url = $.getUrl(queryStatus, data)

                $.get(url).then(data => {
                    if (data.code == '0') {
                        that.handleStatus(data.detail.status);//执行对应状态的操作
                    }
                })
            }
        }, 5000);
    },

    //TODO 考虑在什么时候关闭长连接
    onHide: function () {
        if (!wx.getStorageSync('isRepariPage')) {
            console.log('跳转非保修界面')
            console.log('# logs_onHide()');
            wx.onSocketClose(function (res) {
                console.log('WebSocket 已关闭！');
            });
            //清楚查询定时器
            console.warn('onHide:queryStatusIntervarID' + queryStatusIntervarID + ',wxTimerId' + wxTimerId + ',scanTimer' + wx.getStorageSync('scanTimer') + ',opacityTimer' + wx.getStorageSync('opacityTimer'));
            this.clearTimer()
        }
        //获取之后清空
        // wx.removeStorageSync('timeStart');
    },

    onUnload: function () {
        console.log('# logs_onUnload()');
        wx.removeStorageSync("isRepariPage")

        wx.closeSocket();
        wx.onSocketClose(function (res) {
            console.log('WebSocket 已关闭！');
        });

        console.warn('onUnload:queryStatusIntervarID' + queryStatusIntervarID + ',wxTimerId' + wxTimerId + ',scanTimer' + wx.getStorageSync('scanTimer') + ',opacityTimer' + wx.getStorageSync('opacityTimer'));
        this.clearTimer()
        //获取之后清空
        // wx.removeStorageSync('timeStart');
    },


    /**
     *    METHODS
     */

    clearTimer:function(){
        if (queryStatusIntervarID) clearInterval(queryStatusIntervarID);
        if (wxTimerId) clearInterval(wxTimerId);
        if (wx.getStorageSync('scanTimer')) clearTimeout(wx.getStorageSync('scanTimer'));
        if (wx.getStorageSync('opacityTimer')) clearInterval(wx.getStorageSync('opacityTimer'));
        wxTimer.wxTimerStop()
    },

    callServicePhone: function () {
        wx.makePhoneCall({
            phoneNumber: config.servicePhone
        })
    },

    return_index: function () {
        $.goto(config.page.index)
    },

    return_repair_page: function () {
        wx.showModal({
            title: '柜门无法打开',
            content: config.servicePhone,
            confirmText: '拨打',
            cancelText: '报修',
            confirmColor: '#FF3B30',
            cancelColor: '#007AFF',
            success: function (res) {
                if (res.confirm) {
                    wx.makePhoneCall({
                        phoneNumber: config.servicePhone
                    });
                } else if (res.cancel) {
                    //标注跳转报修界面
                    wx.setStorage({
                        key: 'isRepariPage',
                        data: '1',
                        success: function () {
                            $.goto(config.page.repair + "?maintain_type=20", false)
                        }
                    })

                }
            }
        });
    },

    // 获取当前书格心愿单列表
    wish_list_item: function () {
        var that = this;
        var list = [];


        var isbn_list = wx.getStorageSync('grid_wish_list');
        if (isbn_list.length != 0) {
            that.setData({
                isWishView: 1
            });
        }
        wx.getStorage({
            key: 'wish_detail',
            success: function (res) {
                console.log('长度', res.data.length);
                let isbnList = Array.from(isbn_list)
                let data = Array.from(res.data).filter((item, index) => {
                    if (isbnList.includes(item.isbn)) {
                        return item
                    }

                })
                console.log('心愿单信息', data);
                that.setData({
                    wish_list: data
                });
            },
        });

        // console.log(that.data.wish_list);
    },

    handleStatus: function (status) {
        console.log(`# borrowing_handleStatus(${status})`)
        var that = this;
        wx.setStorageSync('res.data.detail.status', status);

        if (status == '0') {        //请求开柜
            that.setData({
                doorStatus: 0
            });

        } else if (status == '1') {  //打开柜门
            if (that.data.doorStatus != 1) {
                var timeStart = wx.getStorageSync('timeStart') ? wx.getStorageSync('timeStart') : "03:00";
                console.log(`柜门时间timeStart${timeStart}，${wx.getStorageSync('timeStart')}`);
                if (!timeStart) {
                    wx.showToast({
                        title: '开启成功',
                        icon: 'success',
                        duration: 2000
                    });
                }

                wxTimerId = wxTimer.wxTimer.call(this, timeStart, function () {
                    console.log("跳转超时等待页面....");
                    that.setData({
                        startScanFlag: 0,
                        overTimeFlag: 1
                    })
                    wx.vibrateLong();
                }, 1, function () {
                    if (status != 1) {
                        console.info('柜门状态:' + status);
                        clearInterval(wxTimerId);
                    }
                }.bind(this));
            }
            that.setData({
                doorStatus: 1
            });

        } else if (status == '2') {  //打开柜门失败
            console.log("打开失败...");
            that.setData({
                doorStatus: 2
            });

        } else if (status == '3') {  //关门成功
            console.log("已关闭...");
            that.setData({
                doorStatus: 3
            })
        } else if (status == '4') {  //开始盘点
            console.log("开始盘点...");
            that.setData({
                doorStatus: 4
            })
        } else if (status == '5') {                    //盘点成功
            console.log("盘点结束...");
            that.setData({
                doorStatus: 5
            })
            //展示借还书界面
            wx.setStorageSync('detailStatus', true);
            //清除定时
            that.clearTimer()

            // wx.reLaunch({
            //     url: config.page.borrowSuccess
            // });
            $.goto(config.page.borrowSuccess,true)
            //停止执行
        }
    },

})